package com.xqh.study.springtxjms.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * @ClassName CustomerService
 * @Description TODO
 * @Author xuqianghui
 * @Date 2019/12/31 11:25
 * @Version 1.0
 */
@Service
public class CustomerService {

    Logger logger = LoggerFactory.getLogger(CustomerService.class);

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private PlatformTransactionManager transactionManager;

    /**
     * 使用 @JmsListener 监听消息 处理 会有 事务管理. 这种情况下 使用 jmsTemplate发送消息 会在事务中. 有异常 回滚
     * @param msg
     */
    @Transactional //加 @Transactional标签 会开启事务.
    @JmsListener(destination = "customer:msg1:new", containerFactory = "jmsFactory" /*使用配置的 JmsTransactionFactory*/)
    public void handle(String msg){
        logger.info("Get msg1--------->: {}", msg);
        String reply = "Reply1--------->"+msg;
        jmsTemplate.convertAndSend("customer:msg:reply", reply);
        if(msg.contains("error")){
            throw new RuntimeException("some data error");
        }
    }

    /**
     * 代码方式 创建事务.
     * @param msg
     */
    @JmsListener(destination = "customer:msg2:new", containerFactory = "jmsFactory" /*使用配置的 JmsTransactionFactory*/)
    public void handleInCode(String msg){
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            logger.info("Get msg2--------->: {}", msg);
            String reply = "Reply2--------->"+msg;
            jmsTemplate.convertAndSend("customer:msg:reply", reply);
            if(msg.contains("error")){
                throw new RuntimeException("some data error");
            }
            transactionManager.commit(status);
        }catch (Exception e){
            transactionManager.rollback(status);
            throw e;
        }
    }

}
